import 'package:drift/drift.dart';
import 'package:report_sdk/src/models/event.dart';
import 'package:report_sdk/src/storage/storage_backend.dart' as impl;
import 'package:report_sdk/src/database/database.dart';

class StorageBackend implements impl.StorageBackend {
  final ReportSdkDatabase db;

  // 私有构造函数
  StorageBackend() : db = ReportSdkDatabase();

  @override
  Future<void> insertEvent(Event event) async {
    //上报前先插入到数据库
    await db.insertEvent(
      ReportsCompanion.insert(
        id: event.id,
        name: event.name,
        timestampMicros: event.timestampMicros,
        params: event.params == null ? Value.absent() : Value(event.params),
      ),
    );
  }

  @override
  Future<List<Event>> getPendingEventsBatch(int batchSize) async {
    final List<Event> reportList = await db.getPendingEventsBatch(batchSize);
    return reportList;
  }

  @override
  Future<void> deleteBatchEventByIds(List<String> ids) async {
    if (ids.isNotEmpty) {
      await db.deleteEventsByIds(ids);
    }
  }

  @override
  Future<void> cleanOldEvents(int retentionDays) async {
    await db.cleanOldEvents(retentionDays: retentionDays);
  }

  @override
  Future<void> dispose() async {
    await db.close();
  }
}
